home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!news
- From: miker3@ix.netcom.com (Mike Rubenstein)
- Newsgroups: comp.lang.ada,comp.lang.c,comp.lang.c++,comp.edu
- Subject: Re: ANSI C and POSIX (was Re: C/C++ knocks the crap out of Ada)
- Date: Sun, 21 Apr 1996 13:35:04 GMT
- Organization: Netcom
- Message-ID: <317a3715.38162294@nntp.ix.netcom.com>
- References: <4kk9e1$he1@nntp.Stanford.EDU> <dewar.829276268@schonberg> <01bb2ed2.425fb900$65c2b7c7@Zany.localhost>
- NNTP-Posting-Host: ix-dc19-08.ix.netcom.com
- X-NETCOM-Date: Sun Apr 21 8:35:54 AM CDT 1996
- X-Newsreader: Forte Agent .99d/32.182
-
- Bradd W. Szonye <bradds@ix.netcom.com> wrote:
-
- > Try to keep in mind the spirit of defensive programming:
- > If there's something ambiguous about the way you could implement
- > something, and one implementation is safe regardless of how you interpret
- > the ambiguity, the other implementation only works under one specific
- > interpretation, then defensive programming (and portable programming) will
- > encourage the code that works under all circumstances. Consider:
- >
- > for (size_t i = 0; i < 10; i++) do_stuff();
- >
- > versus
- >
- > for (size_t i = 0; i != 10; i++) do_stuff();
- >
- > Even though you *know* that i will never be greater than 10, even though
- > "not equals" should always stop the loop after the tenth iteration,
- > practically every programmer will write the first loop in preference to
- > the second. This has nothing to do with standards; the standards say that
- > i is a local, stack-based variable, not global, and since it is not
- > volatile or referenced by anything else, do_stuff() couldn't modify it,
- > even another thread couldn't modify it. But should your memory chips fail,
- > or do_stuff() accidentally trash the stack with a pointer, then the first
- > loop will never let i get out of the range of 0 <= i < 10, while the
- > second loop might.
-
- What nonsense. Most programmers write the loop the first way out of
- habit and for consistency. Suppose we change the loop a little:
-
- for (size_t i = a; i < 10; i++) do_stuff();
-
- versus
-
- for (size_t i = a; i != 10; i++) do_stuff();
-
- Now the loops mean different things. Either might be correct, but the
- first is by far the more common.
-
- If the stack is trashed or the memory chips have failed, why do you
- want to get out of the loop? Why do you assume that getting out of
- the loop prematurely is better than not getting out of it at all?
- Suppose the loop is part of a sort. If you stay in it, the program
- will hang and the user will complain. If you exit it the program may
- continue and output erroneous information that causes costly errors.
-
- Defensive programming is important, but coding so you'll exit a loop
- even if the hardware fails has nothing to do with it.
-
-
- Michael M Rubenstein
-